<template>
  <div class="app-container">
    <el-container>
      <el-aside width="300px" style="max-height:100%;overflow: auto">
        <div class="head-container">
          <el-input
            v-model="roleInputName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="roleOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="roleTree"
            node-key="id"
            default-expand-all
            :highlight-current="true"
            @node-click="handleNodeClick"
          />
        </div>
      </el-aside>
      <el-main>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="Basic"></el-tab-pane>
        </el-tabs>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:role:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button

              icon="el-icon-edit"
              size="mini"
              :disabled="singleRole"
              @click="handleUpdate"
              v-hasPermi="['system:role:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button

              icon="el-icon-delete"
              size="mini"
              :disabled="singleRole"
              @click="handleDelete"
              v-hasPermi="['system:role:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-view"
              size="mini"
              :disabled="singleRole"
              @click="handleDataScope"
              v-hasPermi="['system:role:edit']"
            >部门权限
            </el-button>
          </el-col>
        </el-row>

        <el-table ref="roleList" v-loading="loading" stripe border :data="roleList" style="width: 100%">
          <el-table-column label="角色名称" prop="rolename"/>
          <el-table-column label="角色编码" prop="rolecode"/>
        </el-table>

        <el-row :gutter="10" class="mb8" style="margin-top: 15px">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              :disabled="singleRole"
              @click="openUserList"
              v-hasPermi="['system:userRole:add']"
            >添加用户到角色
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button

              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="deleteUserList"
              v-hasPermi="['system:userRole:remove']"
            >从角色中删除用户
            </el-button>
          </el-col>
        </el-row>

        <el-table
          ref="roleUserList"
          v-loading="loading"
          stripe border
          :data="roleUserList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          >
          <el-table-column type="selection" width="60" align="center"/>
          <el-table-column label="序号" type="index" align="center">
            <template slot-scope="scope">
              <span>{{ utils.serialNumber(scope,queryParams) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户名" prop="username"/>
          <el-table-column label="真实姓名" prop="realname"/>
          <el-table-column label="电子邮件" prop="email"/>
          <el-table-column label="所属角色" prop="rolenames"/>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      </el-main>
    </el-container>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :modal="false" :appendToBody="false" width="800px" top="50px"
               v-dialog-drag :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属机构" prop="branchcodeName">
          <el-input v-model="form.branchcodeName" placeholder="请选择所属机构" @click.native="openOrganization()"/>
        </el-form-item>
        <el-form-item label="角色编码" prop="rolecode">
          <el-input v-model="form.rolecode" :disabled="addOrEdit" placeholder="请输入角色编码"/>
        </el-form-item>
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="form.rolename" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="业务编码" prop="businesscode">
          <el-input v-model="form.businesscode" placeholder="请输入业务编码"/>
        </el-form-item>
        <el-form-item label="业务名称" prop="roleName">
          <el-input v-model="form.businessname" placeholder="请输入业务名称"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.memo" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
          </el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
            style="max-height: 400px;overflow: auto"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="openDataScope" :modal="false" :appendToBody="false" width="800px"
               top="50px" v-dialog-drag :close-on-click-modal="false">
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.rolename" :disabled="true"/>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="form.rolecode" :disabled="true"/>
        </el-form-item>
        <el-form-item label="部门权限">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动
          </el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="!deptCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
            style="max-height: 400px;overflow: auto"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">保 存</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加人员到角色弹框 -->
    <el-dialog :title="title" :visible.sync="openUserPop" :modal="false" :appendToBody="false" width="800px"
               top="50px" v-dialog-drag :close-on-click-modal="false">
      <el-form ref="queryUserParams" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="queryUserParams.username"
            placeholder="请输入用户名"
            clearable
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input
            v-model="queryUserParams.realname"
            placeholder="请输入真实姓名"
            clearable
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button  icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        stripe border
        ref="userRoleTable"
        :data="userList"
        style="width: 100%"
        >
        <el-table-column type="selection" width="60" align="center"/>
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ utils.serialNumber(scope,queryUserParams) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="username"/>
        <el-table-column label="真实姓名" prop="realname"/>
        <el-table-column label="用户状态" align="center">
          <template slot-scope="scope">
            <span class="label label-danger" v-if="scope.row.status=='S'">停用</span>
            <span v-else-if="scope.row.status=='N'">正常</span>
          </template>
        </el-table-column>
        <el-table-column label="电子邮件" prop="email"/>
        <el-table-column label="所属机构" prop="dept.name"/>
      </el-table>
      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="queryUserParams.pageNum"
        :limit.sync="queryUserParams.pageSize"
        @pagination="openUserList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUserList">保 存</el-button>
        <el-button @click="cancelUserList">取 消</el-button>
      </div>
    </el-dialog>
    <!--    组织机构-->
    <organization :visibles="organization" :branchcode="form.branchinnercode"
                  @closeDialog="closeOrganization"></organization>
  </div>
</template>

<script>
  import {
    listRole,
    getRole,
    delRole,
    delUserRole,
    addRole,
    addUserRole,
    updateRole,
    exportRole,
    dataScope,
    changeRoleStatus,
    roleTreeselect,
  } from "@/api/system/role";
  import {treeselect as menuTreeselect, roleMenuTreeselect} from "@/api/system/menu";
  import {treeselect as deptTreeselect, roleDeptTreeselect} from "@/api/system/dept";
  import {listUser} from "@/api/system/user";

  export default {
    name: "Role",
    components: {},
    data() {
      return {
        //左侧树节点的角色编码
        treeRolecode: null,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 没有点击节点按钮失效
        singleRole: true,
        // 总条数
        total: 0,
        // 用户弹框总条数
        userTotal: 0,
        // 角色表格数据
        roleList: [],
        // 角色人员表格数据
        roleUserList: [],
        // 人员弹框表格数据
        userList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        //菜单弹框参数
        menuExpand: false,
        menuNodeAll: false,
        menuCheckStrictly: true,
        //部门数据弹框参数
        deptExpand: true,
        deptCheckStrictly: true,
        deptNodeAll: false,
        // 菜单列表
        menuOptions: [],
        // 部门列表
        deptOptions: [],
        //角色树列表
        roleOptions: [],
        //组织机构弹框
        organization: false,
        //添加人员到角色弹框
        openUserPop: false,
        roleInputName: null,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          rolename: null,
          rolecode: null
        },
        // 查询参数
        queryUserParams: {
          pageNum: 1,
          pageSize: 10,
          username: null,
          realname: null,
          ids: null,
        },
        //添加修改判断标识
        addOrEdit: false,
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        activeName: 'Basic',
        // 表单校验
        rules: {
          branchcodeName: [
            {required: true, message: "所属机构不能为空", trigger: "blur"}
          ],
          rolename: [
            {required: true, message: "角色名称不能为空", trigger: "blur"}
          ],
          rolecode: [
            {required: true, message: "角色编码不能为空", trigger: "blur"}
          ]
        }
      };
    },
    watch: {
      // 根据名称筛选部门树
      roleInputName(val) {
        this.$refs.roleTree.filter(val);
      }
    },
     created() {
      this.getRoleTreeselect();
    },
    methods: {
      /** 获取角色树节点信息*/
      getCheckRole() {
        this.roleList = [];
        var rolecode = this.queryParams.rolecode;
        getRole(rolecode).then(response => {
          if (response.data != undefined) {
            this.roleList.push(response.data);
            this.treeRolecode = this.roleList[0].rolecode;
          }
          this.loading = false;
        });
      },
      /** 查询角色树 */
      getRoleTreeselect() {
        var that = this;
        roleTreeselect().then(response => {
          this.roleOptions = response.roles;
          if (this.roleOptions.length != 0) {
            this.singleRole = false;
          } else {
            this.singleRole = true;
          }
          this.$nextTick(() => {
            // treeBox 元素的ref   value 绑定的node-key
            this.$refs.roleTree.setCurrentKey(that.selectChildren(response.roles[0]));
            this.treeRolecode = that.selectChildren(response.roles[0]);
            this.handleNodeClick();
          });
        });

      },
      //获取树结构第一条数据
      selectChildren(data) {
        if (data != undefined && data != null) {
          var ids = data.id;
          return ids;
        } else {
          return null;
        }

      },

      /** 查询角色列表 */
      getList() {
        this.loading = true;
        listRole(this.addDateRange(this.queryParams)).then(
          response => {
            this.roleUserList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        menuTreeselect().then(response => {
          this.menuOptions = response.data;
        });
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 所有部门节点数据
      getDeptAllCheckedKeys() {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getCheckedKeys();
        return checkedKeys;
      },
      /** 根据角色ID查询菜单树结构 */
      getRoleMenuTreeselect(rolecode) {
        return roleMenuTreeselect(rolecode).then(response => {
          this.menuOptions = response.menus;
          return response;
        });
      },
      /** 根据角色ID查询部门树结构 */
      getRoleDeptTreeselect(rolecode) {
        return roleDeptTreeselect(rolecode).then(response => {
          this.deptOptions = response.depts;
          return response;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        if (data != undefined && data != null) {
          this.treeRolecode = data.id;
        }
        this.queryParams.rolecode = this.treeRolecode;
        this.getCheckRole();
        this.getList();
      },
      //选项卡方法
      handleClick(tab, event) {
        if (this.treeRolecode != null) {
          this.queryParams.rolecode = this.treeRolecode;
          this.getCheckRole();
          this.getList();
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮（数据权限）
      cancelDataScope() {
        this.openDataScope = false;
        this.reset();
      },
      // 取消按钮（人员弹框）
      cancelUserList() {
        this.openUserPop = false;
        this.queryUserParams.username = null;
        this.queryUserParams.realname = null;
        this.reset();
      },
      //打开组织机构弹框
      openOrganization() {
        this.organization = true;
      },
      //关闭组织机构弹框触发的方法
      closeOrganization(list) {
        if (list != undefined && list != [] && list != null) {
          this.form.branchinnercode = list[0].branchcode;
          this.form.branchcodeName = list[0].name;
          this.$refs.form.clearValidate(['branchcodeName'])
        }
        this.organization = false;
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.menuExpand = false;
        this.menuNodeAll = false;
        this.menuCheckStrictly = false;
        this.deptExpand = true;
        this.deptNodeAll = false;
        this.deptCheckStrictly = false;
        this.form = {
          branchcodeName: undefined,
          businesscode: undefined,
          businessname: undefined,
          rolecode: undefined,
          rolename: undefined,
          memo: undefined,
          branchinnercode: undefined,
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryUserParams.pageNum = 1;
        this.openUserList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryUserParams.pageNum = 1;
        this.queryUserParams.username = null;
        this.queryUserParams.realname = null;
        this.resetForm("queryUserParams");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.username)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        if (type == 'menu') {
          let treeList = this.menuOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
          }
        } else if (type == 'dept') {
          let treeList = this.deptOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        if (type == 'menu') {
          this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
        } else if (type == 'dept') {
          this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
        }
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        if (type == 'menu') {
          this.form.menuCheckStrictly = value ? true : false;
        } else if (type == 'dept') {
          this.form.deptCheckStrictly = value ? true : false;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getMenuTreeselect();
        getRole().then(response => {
          this.form.branchcodeName = response.dept ? response.dept.name : null;
          this.form.branchinnercode = response.dept ? response.dept.branchinnercode: null;
          this.open = true;
          this.title = "添加角色";
          this.addOrEdit = false;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const roleMenu = this.getRoleMenuTreeselect(this.treeRolecode);
        getRole(this.treeRolecode).then(response => {
          console.log(response)
          this.form = response.data;
          this.form.branchcodeName  = response.dept ? response.dept.name : null;
          this.form.branchinnercode = response.dept ? response.dept.branchinnercode: null;
          this.open = true;
          this.$nextTick(() => {
            roleMenu.then(res => {
              this.$refs.menu.setCheckedKeys(res.checkedKeys);
            });
          });
          this.title = "修改角色";
          this.addOrEdit = true;
        });
      },
      /** 分配部门数据权限操作 */
      handleDataScope(row) {
        this.reset();
        const roleDeptTreeselect = this.getRoleDeptTreeselect(this.treeRolecode);
        getRole(this.treeRolecode).then(response => {
          this.form = response.data;
          this.openDataScope = true;
          this.$nextTick(() => {
            roleDeptTreeselect.then(res => {
              this.$refs.dept.setCheckedKeys(res.checkedKeys);
            });
          });
          this.title = "查看数据权限";
        });
      },
      /** 人员弹框 */
      openUserList() {
        this.loading = true;
        //收集角色用户表已添加的id
        this.queryUserParams.ids = this.roleUserList.map(item => item.username).join(',');
        listUser(this.queryUserParams).then(response => {
          this.userList = response.rows;
          this.userTotal = response.total;
          this.loading = false;
          this.title = "添加人员";
        });
        this.openUserPop = true;
      },

      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.addOrEdit) {
              this.form.menuIds = this.getMenuAllCheckedKeys();
              updateRole(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getRoleTreeselect();
              });
            } else {
              this.form.menuIds = this.getMenuAllCheckedKeys();
              addRole(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getRoleTreeselect();

              });
            }
          }
        });
      },
      /** 提交按钮（数据权限） */
      submitDataScope: function () {
        if (this.form.rolecode != undefined) {
          this.form.deptIds = this.getDeptAllCheckedKeys();
          dataScope(this.form).then(response => {
            this.msgSuccess("修改成功");
            this.openDataScope = false;
            this.getList();
          });
        }
      },
      /** 提交按钮（添加人员到角色） */
      submitUserList: function () {
        if (this.treeRolecode != undefined) {
          //获取添加人员到角色表格多选框ID值
          var userIds = this.$refs.userRoleTable.selection.map(item => item.username).join(',');
          if (userIds.length > 0) {
            addUserRole(this.treeRolecode, userIds).then(response => {
              this.msgSuccess("操作成功");
              this.openUserPop = false;
              this.getList();
            });
          } else {
            this.$message({
              message: '请最少选择一条信息',
              type: 'warning'
            });
          }
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        var rolecodes = this.treeRolecode;
        this.$confirm('是否确认删除角色编码为"' + this.treeRolecode + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delRole(rolecodes);
        }).then(() => {
          this.getRoleTreeselect();
          this.msgSuccess("删除成功");
        })
      },
      /** 从角色删除用户 */
      deleteUserList() {
        var that = this;
        this.$confirm('是否确认删除用户名为"' + that.ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delUserRole(that.treeRolecode, that.ids.join(','));
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
    }
  };
</script>
<style lang="less" scoped>
    /deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
      color: rgb(249, 156, 52);
    }
</style>
